package cn.tomoya.module.api.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.tomoya.common.BaseController;
import cn.tomoya.exception.ApiException;
import cn.tomoya.exception.Result;
import cn.tomoya.module.collect.service.CollectService;
import cn.tomoya.module.reply.entity.Reply;
import cn.tomoya.module.reply.service.ReplyService;
import cn.tomoya.module.security.JwtTokenUtil;
import cn.tomoya.module.security.JwtUser;
import cn.tomoya.module.topic.entity.Topic;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * Created by tomoya.
 * Copyright (c) 2016, All Right Reserved.
 * http://tomoya.cn
 */
@RestController
@Api(tags = "留言页面",description = "APP")
public class TopicApiController extends BaseController {

    @Autowired
    private TopicService topicService;
    @Autowired
    private ReplyService replyService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailsService userDetailsService;





    /**
     * 话题详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询留言详情",httpMethod = "GET",notes = "根据id查询留言详情",response = Topic.class)
    @RequestMapping(value = "/api/topic/{id}" ,method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public Result detail( HttpServletRequest request,@PathVariable("id")@ApiParam(value = "留言id",required = true)Integer id) throws ApiException {
        Topic topic = topicService.findById(id);
        if(topic == null) throw new ApiException("话题不存在");
        Map<String, Object> map = new HashMap<>();
        //浏览量+1
        /*topic.setView(topic.getView() + 1);
        topicService.save(topic);//更新话题数据
        List<Reply> replies = replyService.findByTopic(topic);
        map.put("topic", topic);
        map.put("replies", replies);
        map.put("author", topic.getUser());*/
//        map.put("collectCount", collectService.countByTopic(topic));

        String authorization = request.getHeader("Authorization");
        if(authorization!=null){
            JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(authorization);
            String tokenUserName = jwtUsr.getUsername();
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(tokenUserName);
            User user = userService.findByUsername(tokenUserName);
            String username = user.getUsername();
            if(username.equals(tokenUserName)){
                topic.setView(topic.getView() + 1);
                topicService.save(topic);//更新话题数据
                List<Reply> replies = replyService.findByTopic(topic);
                map.put("topic", topic);
                map.put("replies", replies);
                map.put("author", topic.getUser());
                return Result.success(map);
//        map.put("collectCount", collectService.countByTopic(topic))
            } else{
                return Result.error(400,"没有权限");
            }

        }else{
            return Result.error(400,"没有权限");
        }




    }

  /*  @ApiOperation(value = "保存留言",httpMethod = "POST",notes = "保存留言内容信息")
    @RequestMapping(value = "/api/topic/save",method = RequestMethod.POST)
    public Result save(@RequestParam(value = "title")@ApiParam(value = "title")String title,@RequestParam(value = "content")@ApiParam(value = "content")String content,@RequestParam(value = "token")@ApiParam(value = "token")String token){
        JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(token);
        String tokenUserName = jwtUsr.getUsername();
        Result result = new Result();
        if(tokenUserName== null || "".equals(tokenUserName)){
//            跳转登录
            *//*return render("/login");*//*
            result.setDescription("没有登录");
            result.setCode(201);
            return  result;
        }
//        User user = getUser();
        User user=userService.findByUsername(tokenUserName);
        Topic topic = new Topic();
        topic.setContent(content);
        topic.setTitle(title);
        topic.setInTime(new Date());
        topic.setUp(0);
        topic.setView(0);
        topic.setUser(user);
        topic.setGood(false);
        topic.setTop(false);
        topicService.save(topic);
        return result.success(topic);
    }
    */

    @ApiOperation(value = "保存留言",httpMethod = "POST",notes = "保存留言内容信息")
    @RequestMapping(value = "/api/topic/save",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    public Result save(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "提交条件对象title:String,content:String,token:String", required = true) @RequestBody JSONObject topicvo){

        String  title =(String) topicvo.get("title");
        String content = (String)topicvo.get("content");
        String token =(String) topicvo.get("token");
        JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(token);
        String tokenUserName = jwtUsr.getUsername();
        Result result = new Result();

        String errors;
        Topic oldTopic=null;
        if(!StringUtils.isEmpty(title)){
            oldTopic= topicService.findByTitle(title);
        }

        if (StringUtils.isEmpty(title)) {
            errors = "标题不能为空";
        /*}  else if (!siteConfig.getSections().contains(tab)) {
            errors = "版块不存在";*/
            return result.error(201,errors);
        }else if(oldTopic!=null){
            errors="留言主题已经存在";
            return result.error(201,errors);

        }
        if(tokenUserName== null || "".equals(tokenUserName)){
//            跳转登录
            /*return render("/login");*/
            errors="没有登录";
            return result.error(201,errors);
        }
//        User user = getUser();
        User user=userService.findByUsername(tokenUserName);
        Topic topic = new Topic();
        topic.setContent(content);
        topic.setTitle(title);
        topic.setInTime(new Date());
        topic.setUp(0);
        topic.setView(0);
        topic.setUser(user);
        topic.setGood(false);
        topic.setTop(false);
        topicService.save(topic);
        return result.success(topic);
    }




    @ApiOperation(value = "搜索",notes = "根据标题名称搜索",httpMethod = "GET",response = Topic.class)
    @RequestMapping(value = "/api/topic/search/{q}/{size}/{p}",method = RequestMethod.GET)
    public Result search(HttpServletRequest request,@ApiParam(value = "搜索条件q")@PathVariable(value = "q") String q,@ApiParam(value = "每页条数") @PathVariable(value = "size") Integer size,@ApiParam(value = "页数") @PathVariable(value = "p") Integer p){
        Page<Topic> page = topicService.findByTitleLike("%"+q+"%",p==null ?1:p,size);
        String authorization = request.getHeader("Authorization");
        if(authorization!=null){
            JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(authorization);
            String tokenUserName = jwtUsr.getUsername();
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(tokenUserName);
            User user = userService.findByUsername(tokenUserName);
            String username = user.getUsername();
            if(username.equals(tokenUserName)){
                return Result.success(page);
            } else{
                return Result.error(400,"没有权限");
            }

        }else{
            return Result.error(400,"没有权限");
        }

    }
}


